#!/bin/bash

# 日志函数
log() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $1"
}

set -e

# ======================
# 配置参数（按需修改）
# ======================
MQ_VERSION="3.7.23"
ERLANG_VERSION="21.3.8.24"
INSTALL_DIR="$17"
MQ_USER="rabbitmq"
MQ_GROUP="rabbitmq"
MQ_DATA_DIR="$INSTALL_DIR/data"
MQ_LOG_DIR="$INSTALL_DIR/log/"
MQ_CONF_DIR="$INSTALL_DIR/conf"
CLUSTER_NAME="$1"
ADMIN_USER="$2"
ADMIN_PASSWORD="$3"
PORT="$4"
WEB_PORT="$5"
HOSTNAME=$(hostname -s)



adminUser="$2"
adminPassword="$3"
portAmqp="$4"
portManage="$5"
epmdPort="$6"
node1Hostname="$7"
node1Ip="$8"
node1PortAmqp="$9"
node1PortManage="$10"
node1PortMsg="$11"
node2Hostname="$12"
node2Ip="$13"
node2PortAmqp="$14"
node2PortManage="$15"
node2PortMsg="$16"
installPath="$17"


# 验证必填参数
# if [ -z "$clusterName" ]; then
    # echo "错误: --clusterName 参数是必需的" >&2
    # exit 1
# fi

# 打印接收到的参数（调试用）
echo "集群配置:"
echo "  集群名称: $CLUSTER_NAME"
echo "  管理员用户: $adminUser"
echo "  AMQP端口: $portAmqp"
echo "  管理端口: $portManage"
echo "  EPMD端口: $epmdPort"

echo "节点1配置:"
echo "  主机名: $node1Hostname"
echo "  IP地址: $node1Ip"
echo "  AMQP端口: $node1PortAmqp"
echo "  管理端口: $node1PortManage"
echo "  消息端口: $node1PortMsg"

echo "节点2配置:"
echo "  主机名: $node2Hostname"
echo "  IP地址: $node2Ip"
echo "  AMQP端口: $node2PortAmqp"
echo "  管理端口: $node2PortManage"
echo "  消息端口: $node2PortMsg"

# ======================
# 依赖包列表
# ======================
ERLANG_PKG="otp_src_${ERLANG_VERSION}.tar.gz"
RABBITMQ_PKG="rabbitmq-server-generic-unix-${MQ_VERSION}.tar.xz"
DEPS=(
    "socat-1.7.4.2-5.el8.x86_64.rpm"
    "logrotate-3.20.1-6.el8.x86_64.rpm"
    "xz-5.2.4-4.el8.x86_64.rpm"
)

# ======================
# 初始化环境
# ======================
init_environment() {
    log ">>> 初始化安装环境"

    # 创建用户和组
    if ! id -u $MQ_USER >/dev/null 2>&1; then
        groupadd $MQ_GROUP
        useradd -r -d $MQ_DATA_DIR -s /bin/bash -g $MQ_GROUP $MQ_USER
        log "已创建用户: $MQ_USER"
    fi

    # 创建目录结构
    mkdir -p $INSTALL_DIR $MQ_DATA_DIR $MQ_LOG_DIR $MQ_CONF_DIR
    chown -R $MQ_USER:$MQ_GROUP $INSTALL_DIR $MQ_DATA_DIR $MQ_LOG_DIR $MQ_CONF_DIR

    # 设置环境变量
    echo "export PATH=$INSTALL_DIR/rabbitmq_server-$MQ_VERSION/sbin:\$PATH" > /etc/profile.d/rabbitmq.sh
    source /etc/profile.d/rabbitmq.sh
}

# ======================
# 安装依赖包
# ======================
install_dependencies() {
    log ">>> 安装系统依赖"

    # 离线安装 RPM 包
    for pkg in "${DEPS[@]}"; do
        if [ -f "deps/$pkg" ]; then
            log "安装依赖包: $pkg"
            rpm -Uvh --force --nodeps "deps/$pkg"
        else
            log "错误: 依赖包 $pkg 未找到!"
            exit 1
        fi
    done

    # 检查关键命令
    command -v socat >/dev/null 2>&1 || { echo "socat 安装失败!"; exit 1; }
    command -v logrotate >/dev/null 2>&1 || { echo "logrotate 安装失败!"; exit 1; }
    command -v xz >/dev/null 2>&1 || { echo "xz 安装失败!"; exit 1; }
}

# ======================
# 安装 Erlang
# ======================
install_erlang() {
    log ">>> 安装 Erlang $ERLANG_VERSION"

    if [ ! -f "$INSTALL_DIR/$ERLANG_PKG" ]; then
        log "错误: Erlang 安装包未找到!"
        exit 1
    fi

    # 解压到临时目录
    tar -xzf "$INSTALL_DIR/$ERLANG_PKG" -C $INSTALL_DIR
    cd "$INSTALL_DIR/otp_src_${ERLANG_VERSION}"

    # 编译安装
    ./configure --prefix=/usr/local/erlang \
                --without-javac \
                --enable-threads \
                --enable-smp-support \
                --enable-kernel-poll \
                --enable-hipe \
                --enable-shared-zlib \
                --enable-dynamic-ssl-lib \
                --with-ssl

    make -j$(nproc)
    make install

    # 设置环境变量
    echo 'export PATH=/usr/local/erlang/bin:$PATH' >> /etc/profile.d/erlang.sh
    source /etc/profile.d/erlang.sh

    # 验证安装
    if ! command -v erl >/dev/null 2>&1; then
        log "Erlang 安装失败!"
        exit 1
    fi

    echo "Erlang 版本: $(erl -eval '{ok, Version} = file:read_file(filename:join([code:root_dir(), "releases", erlang:system_info(otp_release), "OTP_VERSION"])), io:fwrite(Version), halt().' -noshell)"
}

# ======================
# 安装 RabbitMQ
# ======================
install_rabbitmq() {
    log ">>> 安装 RabbitMQ $MQ_VERSION"

    if [ ! -f "$INSTALL_DIR/$RABBITMQ_PKG" ]; then
        echo "错误: RabbitMQ 安装包未找到!"
        exit 1
    fi

    # 解压安装
    tar -xJf "$INSTALL_DIR/$RABBITMQ_PKG" -C $INSTALL_DIR
    ln -s $INSTALL_DIR/rabbitmq_server-$MQ_VERSION $INSTALL_DIR/current

    # 设置权限
    chown -R $MQ_USER:$MQ_GROUP $INSTALL_DIR
    chmod -R 755 $INSTALL_DIR/current/sbin

    # 创建配置文件
    cat > $MQ_CONF_DIR/rabbitmq.conf <<EOF
# 群集名称
cluster_name = $clusterName
# 网络设置
listeners.tcp.default = $PORT
management.tcp.port = $WEB_PORT

# 数据目录
loopback_users.guest = false
log.file.level = info
log.dir = $MQ_LOG_DIR
log.file = rabbitmq.log

# 内存和磁盘设置
vm_memory_high_watermark.relative = 0.6
disk_free_limit.absolute = 2GB

# 集群设置（可选）
# cluster_formation.peer_discovery_backend = rabbit_peer_discovery_classic_config
# cluster_formation.classic_config.nodes.1 = rabbit@node1
# cluster_formation.classic_config.nodes.2 = rabbit@node2
EOF

    # 设置环境文件
    cat > $MQ_CONF_DIR/rabbitmq-env.conf <<EOF
NODENAME=rabbit@$HOSTNAME
RABBITMQ_MNESIA_BASE=$MQ_DATA_DIR/mnesia
RABBITMQ_LOG_BASE=$MQ_LOG_DIR
RABBITMQ_CONFIG_FILE=$MQ_CONF_DIR/rabbitmq
CONSOLE_LOG="+S +W"
EOF

    chown -R $MQ_USER:$MQ_GROUP $MQ_CONF_DIR
}

# ======================
# 配置系统服务
# ======================
configure_service() {
    log ">>> 配置系统服务"

    # 创建 systemd 服务文件
    cat > /etc/systemd/system/rabbitmq-server.service <<EOF
[Unit]
Description=RabbitMQ broker
After=network.target

[Service]
Type=simple
User=$MQ_USER
Group=$MQ_GROUP
UMask=0027
LimitNOFILE=65536
Environment="HOME=$MQ_DATA_DIR"
Environment="RABBITMQ_MNESIA_BASE=$MQ_DATA_DIR/mnesia"
Environment="RABBITMQ_LOG_BASE=$MQ_LOG_DIR"
Environment="RABBITMQ_CONFIG_FILE=$MQ_CONF_DIR/rabbitmq"
Environment="RABBITMQ_ENV_CONF=$MQ_CONF_DIR/rabbitmq-env.conf"
ExecStart=$INSTALL_DIR/current/sbin/rabbitmq-server
ExecStop=$INSTALL_DIR/current/sbin/rabbitmqctl stop
Restart=on-failure
RestartSec=30

[Install]
WantedBy=multi-user.target
EOF

    # 启用并启动服务
    systemctl daemon-reload
    systemctl enable rabbitmq-server
    systemctl start rabbitmq-server

    # 等待服务启动
    log "等待 RabbitMQ 启动..."
    sleep 10

    # 检查服务状态
    if ! systemctl is-active --quiet rabbitmq-server; then
        log "RabbitMQ 服务启动失败!"
        journalctl -u rabbitmq-server -xe --no-pager
        exit 1
    fi
}

# ======================
# 初始配置
# ======================
initial_configuration() {
    log ">>> 执行初始配置"

    # 启用管理插件
    $INSTALL_DIR/current/sbin/rabbitmq-plugins enable rabbitmq_management

    # 创建管理员用户
    $INSTALL_DIR/current/sbin/rabbitmqctl add_user $ADMIN_USER $ADMIN_PASSWORD
    $INSTALL_DIR/current/sbin/rabbitmqctl set_user_tags $ADMIN_USER administrator
    $INSTALL_DIR/current/sbin/rabbitmqctl set_permissions -p / $ADMIN_USER ".*" ".*" ".*"

    # 删除默认用户
    $INSTALL_DIR/current/sbin/rabbitmqctl delete_user guest

    # 设置策略
    $INSTALL_DIR/current/sbin/rabbitmqctl set_policy ha-all "^" '{"ha-mode":"all","ha-sync-mode":"automatic"}'
}

# ======================
# 安装后检查
# ======================
post_install_check() {
    log ">>> 安装后检查"

    # 检查服务状态
    systemctl status rabbitmq-server --no-pager

    # 检查端口监听
    log "端口监听状态:"
    netstat -tuln | grep -E ":$PORT|:$WEB_PORT"

    # 检查用户列表
    log "用户列表:"
    $INSTALL_DIR/current/sbin/rabbitmqctl list_users

    # 获取管理界面状态
    log "管理界面:"
    curl -s -u $ADMIN_USER:$ADMIN_PASSWORD http://localhost:$WEB_PORT/api/overview | jq .

    log ""
    log "======================================================"
    log "RabbitMQ 安装完成!"
    log "管理界面: http://$(hostname -I | awk '{print $1}'):$WEB_PORT"
    log "用户名: $ADMIN_USER"
    log "密码: $ADMIN_PASSWORD"
    log "AMQP 端口: $PORT"
    log "======================================================"
}

# ======================
# 主安装流程
# ======================
main() {
    # 检查 root 权限
    if [ "$(id -u)" != "0" ]; then
        log "错误: 此脚本必须以 root 权限运行!"
        exit 1
    fi

    log "======================================================"
    log "开始安装 RabbitMQ (离线模式)"
    log "版本: $MQ_VERSION"
    log "主机名: $HOSTNAME"
    log "安装目录: $INSTALL_DIR"
    log "======================================================"

    # 执行安装步骤
    init_environment
    #install_dependencies
    install_erlang
    install_rabbitmq
    configure_service
    initial_configuration
    post_install_check
}

# 执行主函数
# main


log "执行脚本结束"

log "执行脚本结束"

log "执行脚本结束"
